package com.jiuyuan.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import com.jiuyuan.entity.Employee;
import com.jiuyuan.entity.Nation;
import com.jiuyuan.entity.PoliticsStatus;
import com.jiuyuan.entity.vo.RespBean;
import com.jiuyuan.entity.vo.RespPageBean;
import com.jiuyuan.service.*;
import com.sun.org.apache.bcel.internal.generic.NEW;
import io.swagger.annotations.ApiOperation;
import lombok.NonNull;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author jiuyuan
 * @since 2023-02-15
 */
@RestController
@RequestMapping("/employee/basic")
public class EmployeeController {
    @Autowired
    IEmployeeService employeeService;
    @Autowired
    IPoliticsStatusService politicsStatusService;
    @Autowired
    INationService nationService;
    @Autowired
    IPositionService positionService;
    @Autowired
    IJoblevelService joblevelService;
    @Autowired
    IDepartmentService departmentService;

    @ApiOperation("查询所有员工")
    @GetMapping("/")
    public RespPageBean list(
            @RequestParam(value = "currentPage", defaultValue = "1") Integer currentPage,
            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
            Employee employee,
            LocalDateTime[] localDateTimes) {
        //查询所有员工并分页
        return employeeService.allList(currentPage, pageSize, employee, localDateTimes);
    }

    @ApiOperation("获取所有政治面貌")
    @GetMapping("/politicsStatuses")
    public RespBean PoliticsStatuses() {
        return RespBean.success(politicsStatusService.list());
    }

    @ApiOperation("获取所有民族")
    @GetMapping("/nations")
    public RespBean nations() {
        return RespBean.success(nationService.list());
    }

    @ApiOperation("获取所有职称")
    @GetMapping("/joblevels")
    public RespBean joblevels() {
        return RespBean.success(joblevelService.list());
    }

    @ApiOperation("获取所有职位")
    @GetMapping("/positions")
    public RespBean positions() {
        return RespBean.success(positionService.list());
    }

    @ApiOperation("获取所有部门")
    @GetMapping("/departments")
    public RespBean departments() {
        return RespBean.success(departmentService.allList());
    }

    @ApiOperation("获取最大workId")
    @GetMapping("/maxWorkId")
    public RespBean maxWorkId() {
        //当前最大workId+1
        return RespBean.success(employeeService.maxWorkId());
    }


    @ApiOperation("添加员工")
    @PostMapping("/")
    public RespBean add(@RequestBody Employee employee) {
        //额外添加信息，并且需要插入消息表
        return employeeService.add(employee);
    }

    @ApiOperation("删除员工")
    @DeleteMapping("/{id}")
    public RespBean delete(@PathVariable Integer id) {
        if (employeeService.removeById(id)) return RespBean.success("删除成功");
        return RespBean.error("删除失败");
    }

    @ApiOperation("更新员工")
    @PutMapping("/")
    public RespBean update(@RequestBody Employee employee) {

        if (employeeService.updateById(employee)) return RespBean.success("删除成功");
        return RespBean.error("删除失败");
    }

    @ApiOperation("导出员工")
    @GetMapping(value = "/export", produces = "application/octet-stream")
//    @GetMapping(value = "/export")
    public void export(HttpServletResponse resp) {
        List<Employee> employees = employeeService.getEmployeeById(null);
        ExportParams exportParams = new ExportParams("员工表", "员工表", ExcelType.HSSF);
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, Employee.class, employees);

        ServletOutputStream outputStream = null;
        try {
            resp.setHeader("content-type", "application/octet-stream");
            resp.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode("员工表.xls", "UTF-8"));
            outputStream = resp.getOutputStream();
            workbook.write(outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.flush();
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    @ApiOperation("导入员工")
    @PostMapping("/import")
    public RespBean importEmp(MultipartFile file) {
        ImportParams importParams = new ImportParams();
        importParams.setTitleRows(1);
        List<Employee> emplyoees = null;
        try {
            emplyoees = ExcelImportUtil.importExcel(file.getInputStream(), Employee.class, importParams);
            List<Nation> nations = nationService.list();
            List<PoliticsStatus> politicsStatuses = politicsStatusService.list();

            emplyoees.forEach(employee -> {
                //给导入的数据，添加实体类id
                @NonNull String nationName = employee.getNation().getName();
                Nation nation = new Nation(nationName);
                int index = nations.indexOf(nation);
                employee.setNationId(nations.get(index).getId());

                @NonNull String psName = employee.getPoliticsStatus().getName();
                PoliticsStatus ps = new PoliticsStatus(psName);
                int index1 = politicsStatuses.indexOf(ps);
                employee.setPoliticId(politicsStatuses.get(index1).getId());
            });
            if (employeeService.saveBatch(emplyoees)) return RespBean.success("导入成功");
        } catch (Exception e) {
            e.printStackTrace();
        }

        return RespBean.error("导入失败");
    }


}























